<template>
  <div class="app-main-container">
    <transition name="fade">
      <Cropper
        v-if="dialogCropperVisible"
        :option-img="optionImg"
        :fileinfo="fileinfo"
        use-type="PROJECT_IMG"
        :fixed-number="shopId == 106 ? [333, 390] : [1, 1]"
        :auto-upload="false"
        @formSubmit="cropperSubmit"
        @formClose="cropperClose"
      />
    </transition>
    <transition name="fade">
      <Cropper
        v-if="dialogCropperVisibleBg"
        :option-img="optionImg"
        :fileinfo="fileinfo"
        use-type="PROJECT_IMG"
        :fixed-number="[220, 252]"
        :auto-upload="false"
        @formSubmit="cropperSubmitBg"
        @formClose="cropperClose"
      />
    </transition>
    <div class="app-main-title">
      {{ $t('message.xzxm') }}
      <div class="goback" @click="goBack">
        <i class="el-icon-refresh-left" /> {{ $t('message.fhsyy') }}
      </div>
    </div>
    <el-form
      ref="ruleForm"
      :rules="rules"
      :model="projectInfo"
      class="doumee-form"
      label-width="auto"
      label-suffix="："
    >
      <div class="property-title">{{ $t('message.xmsx') }}</div>
      <el-form-item class="form-inline" :label="$t('message.xmmc')" prop="projectName">
        <el-input
          v-model="projectInfo.projectName"
          class="firstitem"
          :placeholder="$t('message.qsr') + $t('message.xmmc')"
          maxlength="50"
        />
      </el-form-item>
      <el-form-item :label="$t('message.smfs')" prop="type">
        <el-radio-group v-model="projectInfo.type">
          <el-radio label="0">{{ $t('message.cd') }}</el-radio>
          <el-radio label="1">{{ $t('message.mp') }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-show="projectInfo.type == 0"
        class="form-inline"
        :label="$t('message.ccsc')"
        :prop="projectInfo.type == 0 ? 'durationSessions' : ''"
      >
        <el-input
          v-model="projectInfo.durationSessions"
          onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          class="firstitem"
          :placeholder="$t('message.qsr') + $t('message.shichan')"
          maxlength="10"
        />
        <el-select
          v-model="filters.sessionTime"
          class="seconditem"
          :placeholder="$t('message.qxz')"
        >
          <el-option
            v-for="item in filters.timeTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-show="projectInfo.type == 0"
        class="form-inline"
        :label="$t('message.qdcc')"
        :prop="projectInfo.type == 0 ? 'sessionBegin' : ''"
      >
        <el-input-number
          v-model="projectInfo.sessionBegin"
          :step="1"
          step-strictly
          :min="1"
        />
      </el-form-item>
      <el-form-item
        v-show="projectInfo.type == 0"
        class="form-inline"
        :label="$t('message.zddccc')"
        :prop="projectInfo.type == 0 ? 'maxSiteCount' : ''"
      >
        <el-radio-group v-model="projectInfo.maxSiteCountFlag">
          <el-radio label="1">{{ $t('message.bxg') }}</el-radio>
          <el-radio label="0">{{ $t('message.xiangou') }}</el-radio>
        </el-radio-group>
        <el-input-number
          v-if="projectInfo.maxSiteCountFlag== 0"
          v-model="projectInfo.maxSiteCount"
          style="margin-left: 20px;"
          :step="1"
          step-strictly
          :min="1"
        />
        <span class="placeholder6 ml20">{{ $t('message.dcdczdcss') }}</span>
      </el-form-item>
      <el-form-item
        class="form-inline"
        :label="$t('message.drdccc')"
      >
        <el-radio-group v-model="projectInfo.isXz">
          <el-radio label="0">{{ $t('message.bxg') }}</el-radio>
          <el-radio label="1">{{ $t('message.xiangou') }}</el-radio>
        </el-radio-group>
        <el-input-number
          v-if="projectInfo.isXz== 1"
          v-model="projectInfo.dayMaxNum"
          :step="1"
          style="margin-left: 20px;"
          step-strictly
          :min="1"
        />
        <span class="placeholder6 ml20">{{ $t('message.drhyzcccs') }}</span>
      </el-form-item>
      <el-form-item class="time-inline" :label="$t('message.yysj')" prop="openTimeList">
        <div
          v-for="(item, index) in projectInfo.openTimeList"
          :key="index"
          class="df_ac mb20"
        >
          <el-time-picker
            v-model="item.openTime"
            is-range
            :range-separator="$t('message.zhi')"
            style="width: 400px"
            :start-placeholder="$t('message.kssj')"
            :end-placeholder="$t('message.jssj')"
            format="HH:mm"
            value-format="HH:mm"
            :placeholder="$t('message.xzsjfw')"
          />
          <i
            v-if="index === projectInfo.openTimeList.length - 1 && index !== 2"
            class="el-icon-circle-plus-outline ml10 pointer"
            style="font-size: 18px"
            @click="openTimeAdd"
          />
          <i
            v-if="index !== 0"
            class="el-icon-delete ml10 pointer"
            style="font-size: 18px; color: #f19795"
            @click="openTimeDel(index)"
          />
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.xmtp')" prop="projectPicture">
        <div class="upload-wrap">
          <el-upload
            :action="uploadFileUrl"
            accept=".jpg,.png"
            :on-change="addFileChange"
            :show-file-list="false"
            :auto-upload="false"
            :data="uploadParam"
            class="device-uploader"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="projectInfo.showProjectPictures"
              class="file"
              :style="
                'background-image: url(' + projectInfo.showProjectPictures + ')'
              "
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImage"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholader tip-style">
            <div>
              {{ $t('message.jycc') }}：{{ shopId == 106 ? "333px X 390px" : "100px X 100px" }}
            </div>
            <div>
              {{ $t('message.zctpsm') }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.bjtp')">
        <div class="upload-wrap">
          <el-upload
            :action="uploadFileUrl"
            accept=".jpg,.png"
            :on-change="addFileChangeBg"
            :show-file-list="false"
            :auto-upload="false"
            :data="uploadParam"
            class="device-uploader"
          >
            <i class="el-icon-plus uploader-icon" />
            <div
              v-show="projectInfo.showBgPic"
              class="file"
              :style="'background-image: url(' + projectInfo.showBgPic + ')'"
            >
              <div class="delete">
                <i
                  class="el-icon-delete icon"
                  @click.stop="deleteDeviceConfigAddImageBg"
                />
              </div>
            </div>
          </el-upload>
          <div class="placeholader tip-style">
            <div>{{ $t('message.jycc') }}：220px X 252px</div>
            <div>
              {{ $t('message.zctpsm') }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item class="form-inline" :label="$t('message.xmzt')" prop="status">
        <el-select
          v-model="projectInfo.status"
          class="firstitem"
          style="width: 200px"
          :placeholder="$t('message.qxz')"
        >
          <el-option
            v-for="item in filters.businessStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-show="projectInfo.type == 0"
        class="form-inline"
        :label="$t('message.dctxrs')"
        :prop="projectInfo.type == 0 ? 'peerNum' : ''"
      >
        <div class="peerNum-wrap">
          <el-radio
            v-model="peerNumFlag"
            label="1"
            @change="peerNumChange"
          >{{ $t('message.bxz') }}</el-radio>
          <el-radio v-model="peerNumFlag" label="0">{{ $t('message.xianzhi') }}</el-radio>
          <el-input
            v-if="peerNumFlag == '0'"
            v-model="projectInfo.peerNum"
            maxlength="10"
            oninput="value=value.replace(/[^\d]/g,'')"
            class="firstitem"
            style="width: 200px"
            type="text"
          />
          <span v-if="peerNumFlag == '0'" class="ab_right">{{ $t('message.ren') }}</span>
        </div>
      </el-form-item>
      <el-form-item
        v-show="projectInfo.type == 0"
        class="form-inline"
        :label="$t('message.zcqc')"
        :prop="projectInfo.type == 0 ? 'isFull' : ''"
      >
        <el-switch v-model="projectInfo.isFull" />
        <span class="tip-style">{{ $t('message.kqxmzcqcbc') }}</span>
      </el-form-item>
      <el-form-item
        v-show="projectInfo.type == 0"
        :label="$t('message.ccmrjg')"
        :prop="projectInfo.type == 0 ? 'defaultPrice' : ''"
      >
        <el-input
          v-model="projectInfo.defaultPrice"
          style="width: 300px"
          maxlength="10"
          onkeyup="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
          oninput="if(value<0) { value = ''} else {value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')}"
          :placeholder="$t('message.szccjgmrzs')"
        />
      </el-form-item>
      <el-form-item :label="$t('message.sort')" prop="sort">
        <el-input
          v-model="projectInfo.sort"
          maxlength="10"
          oninput="value=value.replace(/[^\d]/g,'')"
          :placeholder="$t('message.qszpxm')"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          :loading="subLoading"
          type="primary"
          @click="submitForm('ruleForm')"
        >{{ $t('message.qrtj') }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { addProject, getProjectInfo, updateProject, uploadFile } from '@/api'
import Cropper from '@/components/cropper'
export default {
  name: 'ProjectAdd',
  components: {
    Cropper
  },
  data() {
    return {
      copName: '',
      shopId: localStorage.getItem('shopId'),
      subLoading: false,
      imageList: [],
      dialogCropperVisible: false,
      dialogCropperVisibleBg: false,
      optionImg: '',
      files: {},
      fileinfo: {},
      projectInfo: {
        projectName: '',
        type: '0',
        isXz: '0',
        durationSessions: '',
        sessionBegin: 0,
        maxSiteCount: 0,
        openTime: [],
        openTimeList: [
          {}
        ],
        projectPicture: '',
        showProjectPictures: '',
        bgPic: '',
        showBgPic: '',
        status: '1',
        maxSiteCountFlag: '1',
        isFull: false,
        sort: '',
        peerNum: ''
      },
      peerNumFlag: '1',
      logo: [],
      uploadFileUrl: uploadFile,
      uploadParam: {
        folder: 'PROJECT_IMG'
      },
      filters: {
        sessionTime: '1',
        orderTime: '1',
        timeTypes: [
          { value: '1', label: this.$t('message.shi2') },
          { value: '0', label: this.$t('message.fen2') }
        ],
        status: '1',
        businessStatus: [
          { value: '1', label: this.$t('message.qy') },
          { value: '0', label: this.$t('message.jy') }
        ]
      },
      rules: {
        projectName: [{ required: true, message: this.$t('message.qsr') + this.$t('message.xmmc'), trigger: 'blur' }],
        durationSessions: [{ required: true, message: this.$t('message.qsr') + this.$t('message.ccsc'), trigger: 'blur' }],
        maxSiteCount: [{ required: true, message: this.$t('message.qsr') + this.$t('message.zddccc'), trigger: 'blur' }],
        openTimeList: [{ type: 'array', required: true, message: this.$t('message.qxz') + this.$t('message.yysj'), trigger: 'change' }],
        type: [{ required: true, message: this.$t('message.qxz') + this.$t('message.smfs'), trigger: 'change' }],
        projectPicture: [{ required: true, message: this.$t('message.qsc') + this.$t('message.xmtp'), trigger: 'change' }],
        status: [{ required: true, message: this.$t('message.qxz') + this.$t('message.yyzt'), trigger: 'change' }],
        defaultPrice: [{ required: true, message: this.$t('message.qsr') + this.$t('message.ccmrjg'), trigger: 'blur' }],
        sort: [{ required: true, message: this.$t('message.qsr') + this.$t('message.sort'), trigger: 'blur' }]
      }
    }
  },
  created() {
    if (this.$route.query.id) {
      this.copName = this.$t('message.bjxm')
      this.getProjectDetailInfo(this.$route.query.id)
    } else {
      const venueInfo = JSON.parse(sessionStorage.getItem('venueInfo'))
      if (venueInfo && venueInfo.openTimeStart && venueInfo.openTimeEnd) {
        this.$set(this.projectInfo, 'openTime', [venueInfo.openTimeStart, venueInfo.openTimeEnd])
      }
    }
  },
  methods: {
    // 提交
    onSubmit() {
      const that = this
      const { filters, projectInfo } = this
      if (projectInfo.isXz && projectInfo.isXz === '1') {
        if (!projectInfo.dayMaxNum) {
          return this.$message.warning(this.$t('message.qsr') + this.$t('message.drhyzddccc'))
        }
      } else {
        projectInfo.dayMaxNum = 0
      }
      if (projectInfo.maxSiteCountFlag === '1') {
        projectInfo.maxSiteCount = 0
      }
      const timeSlots = projectInfo.openTimeList.map(item => {
        if (item.openTime && item.openTime.length > 0) {
          return {
            openTimeStart: item.openTime[0],
            openTimeEnd: item.openTime[1]
          }
        }
      })
      const param = {
        type: projectInfo.type,
        isXz: projectInfo.isXz,
        dayMaxNum: projectInfo.dayMaxNum,
        projectName: projectInfo.projectName,
        projectPicture: projectInfo.projectPicture,
        bgPic: projectInfo.bgPic,
        status: projectInfo.status === '1' ? '1' : '0',
        sort: projectInfo.sort,
        timeSlots,
        venueId: sessionStorage.getItem('venueId')
      }
      if (projectInfo.type === '0') {
        param.durationSessions = filters.sessionTime === '1'
          ? projectInfo.durationSessions * 60
          : projectInfo.durationSessions
        param.sessionBegin = projectInfo.sessionBegin
        param.maxSiteCount = projectInfo.maxSiteCount
        param.peerNum = projectInfo.peerNum
        param.isFull = projectInfo.isFull ? '1' : '0'
        param.defaultPrice = projectInfo.defaultPrice
      }
      if (this.$route.query.id) {
        param.id = this.$route.query.id
      }
      that.subLoading = true
      if (this.$route.query.id) {
        updateProject({ param })
          .then((res) => {
            that.subLoading = false
            if (res.errorCode === '000000') {
              this.$message.success(this.$t('message.editcg'))
              this.$router.replace(`/venueArea/projectList?renovate=1`)
            }
          })
          .catch((er) => {
            that.subLoading = false
            console.log(er)
          })
      } else {
        addProject({ param })
          .then((res) => {
            that.subLoading = false
            if (res.errorCode === '000000') {
              this.$message.success(this.$t('message.addcg'))
              this.$router.replace(`/venueArea/projectList?renovate=1`)
            }
          })
          .catch((err) => {
            that.subLoading = false
            console.log(err)
          })
      }
    },
    // 获取项目详情
    getProjectDetailInfo(id) {
      getProjectInfo({
        param: { id: id }
      })
        .then((res) => {
          if (res.errorCode === '000000') {
            const projectInfo = { ...res.record }
            projectInfo.bgPic = res.record.bgPic || ''
            projectInfo.showBgPic = res.record.showBgPic || ''
            this.filters.orderTime = '0'
            this.filters.sessionTime = '0'
            projectInfo.isFull = res.record.isFull === '1'
            projectInfo.isXz = projectInfo.isXz || '0'
            projectInfo.maxSiteCountFlag = projectInfo.maxSiteCount > 0 ? '0' : '1'
            this.peerNumFlag = projectInfo.peerNum > 0 ? '0' : '1'
            projectInfo.openTime = [projectInfo.openTimeStart, projectInfo.openTimeEnd]
            if (projectInfo.timeSlots && projectInfo.timeSlots.length > 0) {
              const temp = projectInfo.timeSlots.map(item => {
                return { openTime: [item.openTimeStart, item.openTimeEnd] }
              })
              console.log(123, temp)
              projectInfo.openTimeList = temp
            } else {
              projectInfo.openTimeList = []
            }
            if (!res.record.maxSiteCount) {
              projectInfo.maxSiteCount = '0'
            }
            this.projectInfo = projectInfo
            this.showProjectPicture()
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    openTimeAdd() {
      this.projectInfo.openTimeList.push({})
    },
    openTimeDel(i) {
      this.projectInfo.openTimeList.splice(i, 1)
    },
    // 同行人数
    handleChange(value) {
      console.log(value)
    },
    peerNumChange() {
      this.projectInfo.peerNum = 0
    },
    changeType(value) {
      this.projectInfo.durationSessions = ''
      this.projectInfo.sessionBegin = ''
      this.projectInfo.peerNum = ''
      this.projectInfo.isFull = ''
      this.projectInfo.defaultPrice = ''
    },
    showProjectPicture() {
      const imageList = []
      if (this.projectInfo.showProjectPictures) {
        imageList.push({
          url: this.projectInfo.showProjectPictures,
          response: {
            insertUrl: this.projectInfo.projectPicture,
            showUrl: this.projectInfo.showProjectPictures
          }
        })
        this.imageList = [this.projectInfo.projectPicture]
      }
      this.imageList = imageList
    },
    // 上传成功
    uploadSuccess(response, file, fileList) {
      this.projectInfo.projectPicture = fileList[0].response.insertUrl
      this.$refs.ruleForm.clearValidate()
    },
    // 上传图片，开始裁剪
    async addFileChange(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisible = true
      })
    },
    // 裁剪确定按钮
    cropperSubmit(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.projectInfo.projectPicture = config.insertUrl
        this.projectInfo.showProjectPictures = config.showUrl
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisible = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.dialogCropperVisible = false
        this.$refs.ruleForm.clearValidate()
      }
    },
    // 上传图片，开始裁剪
    async addFileChangeBg(file) {
      // 上传，拿到file文件
      this.files = file.raw
      this.$nextTick(() => {
        this.optionImg = URL.createObjectURL(file.raw)
        this.fileinfo = file.raw
        this.dialogCropperVisibleBg = true
      })
    },
    // 裁剪确定按钮
    cropperSubmitBg(config) {
      // preImg 完整路径  urlPre 不包含域名
      if (config.success) {
        this.projectInfo.bgPic = config.insertUrl
        this.projectInfo.showBgPic = config.showUrl
        this.$refs.ruleForm.clearValidate()
        this.dialogCropperVisibleBg = false
      } else {
        this.$message.error(config.msg || this.$t('message.scsb'))
        this.dialogCropperVisibleBg = false
        this.$refs.ruleForm.clearValidate()
      }
    },
    // 裁剪取消
    cropperClose() {
      this.dialogCropperVisible = false
      this.dialogCropperVisibleBg = false
    },
    // 图片移除
    deleteDeviceConfigAddImage() {
      this.projectInfo.projectPicture = ''
      this.projectInfo.showProjectPictures = ''
    },
    deleteDeviceConfigAddImageBg() {
      this.projectInfo.bgPic = ''
      this.projectInfo.showBgPic = ''
    },
    UploadUrl: function() {
      return uploadFile
    },
    submitForm(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.onSubmit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 返回上一页
    goBack() {
      this.$router.replace(`/venueArea/projectList`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.device-uploader {
  width: 80px;
  height: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  cursor: pointer;
  border: 1px dashed #ccc;
  border-radius: 8px;
  transition: all 0.3s;
  margin-right: 20px;
  &:hover {
    border-color: $menuActive;
    .uploader-icon {
      color: $menuActive;
    }
  }
  ::v-deep .el-upload {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    .file {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-size: contain;
      background-position: center;
      background-repeat: no-repeat;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      .delete {
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        display: none;
        align-items: center;
        justify-content: center;
        .icon {
          color: #fff;
        }
      }
      &:hover {
        .delete {
          display: flex;
        }
      }
    }
  }
  .uploader-icon {
    color: #aaaaaa;
    font-size: 22px;
    transition: all 0.3s;
  }
}
.upload-wrap {
  display: flex;
  .placeholader {
    div {
      line-height: 24px;
    }
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}
.peerNum-wrap {
  position: relative;
  // .ab_right{
  //   position: absolute;
  //   left: 200px;
  // }
}
.form-inline {
  .firstitem {
    width: 400px;
    margin-right: 10px;
  }
  .seconditem {
    width: 80px;
    margin-right: 10px;
  }
}
.time-inline {
  .item {
    width: 200px;
  }
  .line {
    width: 20px;
    margin-left: 20px;
    text-align: center;
  }
}
</style>
